/*
simulationClient.c

Author: Jesse Niekraszewicz
Date: April 5, 2012

For: SYSC 4907 Engineering Project

Description: 
receives UDP packets from the Migration Simulator, displays them to the screen or uses the packets to calculate statistics

Arguments: none
*/

#include <stdlib.h>
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdbool.h>
#include <arpa/inet.h>
#include <string.h>
#include <errno.h>


#define COM_PORT 8887
#define BUFFSIZE 1024


//main function that initiates the 2 threads
int main(int argc, char *argv[]){

	int serverSocket;
	int *recv_data;
	int bytesReceived;
	struct sockaddr_in serverAddr, myAddr;
	socklen_t sockLength;
	
	recv_data = malloc(BUFFSIZE);
	memset(&serverAddr,0,sizeof(serverAddr));
	
	printf("Starting simulation client \n");
	
	//create a UDP socket
	serverSocket = socket(AF_INET, SOCK_DGRAM, 0);
	if (serverSocket < 0){
		printf("ERROR: could not create COM socket\n");
		exit(1);
	}
	
	printf("C 1\n");

	myAddr.sin_family = AF_INET;
	myAddr.sin_port = htons(COM_PORT); //the port to bind to
	myAddr.sin_addr.s_addr = INADDR_ANY; // the IP Address to bind to
	bzero(&(myAddr.sin_zero),8); //set all bits to 0

	//bind to the socket
	if(bind(serverSocket,(struct sockaddr*) &myAddr, sizeof(myAddr)) < 0){
		printf("ERROR: could not bind to COM socket %i\n",COM_PORT);
		printf( "Error : %s\n", strerror( errno ));
		exit(1);
	}	
	
	sockLength = sizeof(serverAddr);
	while(1){
		printf("waiting for message");
		bytesReceived = recvfrom(serverSocket,recv_data,BUFFSIZE,0,(struct sockaddr*) &serverAddr,&sockLength);
		printf("C 2\n");
		if (bytesReceived < 0){
			printf("ERROR: Failed to recieve COM message\n");
			printf( "Error : %s\n", strerror( errno ));
		}
		while(bytesReceived > 0){
			//display the message received
			printf("Received message from %s: %i\n",inet_ntoa(serverAddr.sin_addr),(int)*recv_data);
	
			//recieve message from the server
			bytesReceived = recvfrom(serverSocket,recv_data,BUFFSIZE,0,(struct sockaddr*) &serverAddr,&sockLength);
			if (bytesReceived < 0){
				printf("ERROR: Failed to recieve COM message\n");
				printf( "Error : %s\n", strerror( errno ));
			}
		}
	}
	
	return 0;
}
